// src/services/api.js
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';

const API_BASE_URL = 'http://192.168.1.10:3000'; // Android 模拟器访问本地服务器

let token = null;

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器，添加认证token
api.interceptors.request.use(
  async (config) => {
    // 检查是否有token，如果没有则从存储中获取
    if (!token) {
      const storedToken = await AsyncStorage.getItem('userToken');
      if (storedToken) {
        token = storedToken;
      }
    }
    
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    console.log('请求URL:', config.url, '请求方法:', config.method, 'Token状态:', !!token);
    console.log('Authorization header:', config.headers.Authorization);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器，处理通用错误
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response) {
      // 服务器返回错误状态码
      console.error('服务器错误', error.response.status, ':', error.response.data);
      // 特殊处理未授权访问
      if (error.response.status === 401) {
        // Token过期或无效，清除本地存储
        AsyncStorage.removeItem('userToken');
        token = null;
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.error('网络错误: 没有收到响应');
    } else {
      // 其他错误
      console.error('请求错误:', error.message);
    }
    return Promise.reject(error);
  }
);

export default {
  // 设置认证token
  setToken: async (newToken) => {
    token = newToken;
    // 将token保存到持久化存储中
    await AsyncStorage.setItem('userToken', newToken);
    // 同时更新axios实例的默认header
    api.defaults.headers.common['Authorization'] = `Bearer ${newToken}`;
  },
  
  // 清除认证token
  clearToken: async () => {
    token = null;
    // 从持久化存储中清除token
    await AsyncStorage.removeItem('userToken');
    // 同时清除axios实例的默认header
    delete api.defaults.headers.common['Authorization'];
  },

  // 用户登录
  login: async (phone, password) => {
    try {
      const response = await api.post('/auth/login', { phone, password });
      return response.data;
    } catch (error) {
      console.error('登录API错误:', error);
      throw error;
    }
  },

  // 用户注册
  register: async (phone, password, name) => {
    try {
      const response = await api.post('/auth/register', { phone, password, name });
      return response.data;
    } catch (error) {
      console.error('注册API错误:', error);
      throw error;
    }
  },

  // Google登录
  googleLogin: async (accessToken) => {
    try {
      const response = await api.post('/auth/google/login', { accessToken });
      return response.data;
    } catch (error) {
      console.error('Google登录API错误:', error);
      throw error;
    }
  },

  // Facebook登录
  facebookLogin: async (accessToken) => {
    try {
      const response = await api.post('/auth/facebook/login', { accessToken });
      return response.data;
    } catch (error) {
      console.error('Facebook登录API错误:', error);
      throw error;
    }
  },

  // WeChat登录
  wechatLogin: async (accessToken) => {
    try {
      const response = await api.post('/auth/wechat/login', { accessToken });
      return response.data;
    } catch (error) {
      console.error('WeChat登录API错误:', error);
      throw error;
    }
  },

  // 获取当前用户信息
  getCurrentUser: async () => {
    try {
      console.log('获取当前用户信息，Token:', token);
      const response = await api.get('/users/me');
      return response.data;
    } catch (error) {
      console.error('获取当前用户信息API错误:', error);
      throw error;
    }
  },

  // 发送滑动操作（喜欢/不喜欢）
  sendSwipeAction: async (targetUserId, action) => {
    try {
      // 验证参数
      if (!targetUserId || !action) {
        throw new Error('缺少必要参数');
      }
      
      if (!['like', 'dislike'].includes(action)) {
        throw new Error('无效的操作类型');
      }
      
      const response = await api.post('/matches/swipe', { targetUserId, action });
      return response.data;
    } catch (error) {
      console.error('发送滑动操作API错误:', error);
      throw error;
    }
  },

  // 保存筛选条件
  saveFilters: async (filters) => {
    try {
      const response = await api.post('/matches/filters', filters);
      return response.data;
    } catch (error) {
      console.error('保存筛选条件API错误:', error);
      throw error;
    }
  },

  // 获取筛选条件
  getFilters: async () => {
    try {
      const response = await api.get('/matches/filters');
      return response.data;
    } catch (error) {
      console.error('获取筛选条件API错误:', error);
      throw error;
    }
  },

  // 根据筛选条件获取用户
  getFilteredUsers: async (filters) => {
    try {
      const response = await api.get(`/matches?preferences=${encodeURIComponent(JSON.stringify(filters))}`);
      return response.data;
    } catch (error) {
      console.error('获取筛选用户API错误:', error);
      throw error;
    }
  },

  // 获取聊天消息
  getMessages: async (conversationId) => {
    try {
      const response = await api.get(`/chat/messages/${conversationId}`);
      return response.data;
    } catch (error) {
      console.error('获取消息API错误:', error);
      throw error;
    }
  },

  // 获取会话列表
  getConversations: async () => {
    try {
      const response = await api.get('/chat/conversations');
      return response.data;
    } catch (error) {
      console.error('获取会话列表API错误:', error);
      throw error;
    }
  },

  // 获取点赞列表
  getLikes: async () => {
    try {
      const response = await api.get('/users/likes');
      return response.data;
    } catch (error) {
      console.error('获取点赞列表API错误:', error);
      throw error;
    }
  },

  // 获取访客列表
  getVisitors: async () => {
    try {
      const response = await api.get('/users/visitors');
      return response.data;
    } catch (error) {
      console.error('获取访客列表API错误:', error);
      throw error;
    }
  },

  // 获取新匹配列表
  getNewMatches: async () => {
    try {
      const response = await api.get('/matches/new');
      return response.data;
    } catch (error) {
      console.error('获取新匹配列表API错误:', error);
      throw error;
    }
  },

  // 获取用户资料
  getUserProfile: async (userId) => {
    try {
      const response = await api.get(`/users/${userId}`);
      return response.data;
    } catch (error) {
      console.error('获取用户资料API错误:', error);
      throw error;
    }
  },

  // 更新用户个人资料
  updateUserProfile: async (profileData) => {
    try {
      const response = await api.put('/users/profile', profileData);
      return response.data;
    } catch (error) {
      console.error('更新用户个人资料API错误:', error);
      throw error;
    }
  },

  // 更新用户位置信息
  updateUserLocation: async (locationData) => {
    try {
      const response = await api.put('/users/location', locationData);
      return response.data;
    } catch (error) {
      console.error('更新用户位置信息API错误:', error);
      throw error;
    }
  },

  // 获取用户统计数据
  getUserStats: async () => {
    try {
      const response = await api.get('/users/stats');
      return response.data;
    } catch (error) {
      console.error('获取用户统计数据API错误:', error);
      throw error;
    }
  },

  // 动态相关API
  // 发布动态
  createFeed: async (feedData) => {
    try {
      const response = await api.post('/feeds', feedData);
      return response.data;
    } catch (error) {
      console.error('发布动态API错误:', error);
      throw error;
    }
  },

  // 获取动态列表
  getFeeds: async (page = 1, limit = 10) => {
    try {
      const response = await api.get(`/feeds?page=${page}&limit=${limit}`);
      return response.data;
    } catch (error) {
      console.error('获取动态列表API错误:', error);
      throw error;
    }
  },

  // 根据用户ID获取动态
  getUserFeeds: async (userId) => {
    try {
      const response = await api.get(`/feeds/user/${userId}`);
      return response.data;
    } catch (error) {
      console.error('获取用户动态API错误:', error);
      throw error;
    }
  },

  // 删除动态
  deleteFeed: async (feedId) => {
    try {
      const response = await api.delete(`/feeds/${feedId}`);
      return response.data;
    } catch (error) {
      console.error('删除动态API错误:', error);
      throw error;
    }
  },

  // 评论相关API
  // 添加评论
  addComment: async (postId, content) => {
    try {
      const response = await api.post('/comments', { postId, content });
      return response.data;
    } catch (error) {
      console.error('添加评论API错误:', error);
      throw error;
    }
  },

  // 获取动态的所有评论
  getComments: async (postId) => {
    try {
      const response = await api.get(`/comments/post/${postId}`);
      return response.data;
    } catch (error) {
      console.error('获取评论API错误:', error);
      throw error;
    }
  },

  // 删除评论
  deleteComment: async (commentId) => {
    try {
      const response = await api.delete(`/comments/${commentId}`);
      return response.data;
    } catch (error) {
      console.error('删除评论API错误:', error);
      throw error;
    }
  },

  // 点赞相关API
  // 点赞或取消点赞动态
  togglePostLike: async (postId) => {
    try {
      const response = await api.post(`/likes/post/${postId}`);
      return response.data;
    } catch (error) {
      console.error('点赞API错误:', error);
      throw error;
    }
  },

  // 获取动态的点赞状态和数量
  getPostLikeInfo: async (postId) => {
    try {
      const response = await api.get(`/likes/post/${postId}`);
      return response.data;
    } catch (error) {
      console.error('获取点赞信息API错误:', error);
      throw error;
    }
  },

  // VIP相关API
  // 获取VIP套餐
  getVipPackages: async () => {
    try {
      const response = await api.get('/vip/packages');
      return response.data;
    } catch (error) {
      console.error('获取VIP套餐API错误:', error);
      throw error;
    }
  },

  // 购买VIP
  purchaseVip: async (packageId) => {
    try {
      // 参数验证
      if (!packageId) {
        throw new Error('缺少套餐ID');
      }
      
      const response = await api.post('/vip/purchase', { packageId });
      return response.data;
    } catch (error) {
      console.error('购买VIP API错误:', error);
      throw error;
    }
  },

  // 获取用户VIP状态
  getUserVipStatus: async () => {
    try {
      const response = await api.get('/vip/status');
      return response.data;
    } catch (error) {
      console.error('获取用户VIP状态API错误:', error);
      throw error;
    }
  },

  // 充值粉钻
  rechargeDiamonds: async (amount, diamonds) => {
    try {
      // 参数验证
      if (!amount || !diamonds) {
        throw new Error('缺少必要参数');
      }
      
      if (amount <= 0 || diamonds <= 0) {
        throw new Error('参数必须大于0');
      }
      
      const response = await api.post('/vip/recharge', { amount, diamonds });
      return response.data;
    } catch (error) {
      console.error('充值粉钻API错误:', error);
      throw error;
    }
  },

  // 获取粉钻交易记录
  getDiamondTransactions: async () => {
    try {
      const response = await api.get('/vip/transactions');
      return response.data;
    } catch (error) {
      console.error('获取粉钻交易记录API错误:', error);
      throw error;
    }
  },

  // 创建 PayPal 充值订单
  createPaypalOrder: async (amount, diamonds) => {
    try {
      // 参数验证
      if (!amount || !diamonds) {
        throw new Error('缺少必要参数');
      }
      
      if (amount <= 0 || diamonds <= 0) {
        throw new Error('参数必须大于0');
      }
      
      const response = await api.post('/vip/paypal/create', { amount, diamonds });
      return response.data;
    } catch (error) {
      console.error('创建PayPal订单API错误:', error);
      throw error;
    }
  },

  // 执行 PayPal 充值
  executePaypalOrder: async (orderId) => {
    try {
      // 参数验证
      if (!orderId) {
        throw new Error('缺少订单ID');
      }
      
      const response = await api.post('/vip/paypal/execute', { orderId });
      return response.data;
    } catch (error) {
      console.error('执行PayPal充值API错误:', error);
      throw error;
    }
  },

  // 获取适用于用户所在地区的支付方式
  getPaymentMethods: async () => {
    try {
      const response = await api.get('/payment-methods');
      return response.data;
    } catch (error) {
      console.error('获取支付方式API错误:', error);
      throw error;
    }
  },

  // 处理支付
  processPayment: async (paymentData) => {
    try {
      const response = await api.post('/payment-methods/process', paymentData);
      return response.data;
    } catch (error) {
      console.error('处理支付API错误:', error);
      throw error;
    }
  },
};